#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版A股筛选脚本 - 用于测试
"""

import akshare as ak
import pandas as pd
from datetime import datetime

print("="*80)
print("A股股票筛选测试版".center(80))
print("="*80)
print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")

# 第1步：获取所有股票
print("[1] 获取A股实时行情...")
try:
    all_stocks = ak.stock_zh_a_spot_em()
    print(f"  ✓ 获取 {len(all_stocks)} 支股票")
    print(f"\n列名: {list(all_stocks.columns[:10])}")
except Exception as e:
    print(f"  ✗ 失败: {e}")
    exit(1)

# 第2步：基础过滤
print("\n[2] 基础过滤...")
df = all_stocks.copy()

# 排除ST、退市
df = df[~df['名称'].str.contains('ST|退|N', na=False)]
print(f"  排除ST/退市后: {len(df)} 支")

# 排除北交所
df = df[~df['代码'].str.startswith(('4', '8'))]
print(f"  排除北交所后: {len(df)} 支")

# 股价7-50元
df = df[(df['最新价'] >= 7) & (df['最新价'] <= 50)]
print(f"  股价7-50元: {len(df)} 支")

# 成交额>5000万
if '成交额' in df.columns:
    df = df[df['成交额'] >= 50_000_000]
    print(f"  成交额>5000万: {len(df)} 支")

# 总市值>50亿
if '总市值' in df.columns:
    df = df[df['总市值'] >= 50_00_000_000]
    print(f"  市值>50亿: {len(df)} 支")

# PE筛选
if '市盈率-动态' in df.columns:
    df = df[(df['市盈率-动态'] >= 5) & (df['市盈率-动态'] <= 30)]
    print(f"  PE 5-30: {len(df)} 支")

# PB筛选
if '市净率' in df.columns:
    df = df[(df['市净率'] >= 0.8) & (df['市净率'] <= 5)]
    print(f"  PB 0.8-5: {len(df)} 支")

print(f"\n基础过滤后剩余: {len(df)} 支")

if len(df) == 0:
    print("✗ 筛选结果为空，请检查条件")
    exit(0)

# 第3步：显示结果
print("\n[3] 筛选结果 Top 20:\n")
result = df[['代码', '名称', '最新价', '涨跌幅', '成交额', '总市值', 
             '市盈率-动态', '市净率', '换手率']].head(20).copy()

# 格式化
result['成交额(亿)'] = (result['成交额'] / 100_000_000).round(2)
result['总市值(亿)'] = (result['总市值'] / 100_000_000).round(2)
result = result.drop(['成交额', '总市值'], axis=1)

from tabulate import tabulate
print(tabulate(result, headers='keys', tablefmt='grid', showindex=False))

# 导出Excel
filename = f"筛选结果_简化版_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
try:
    result.to_excel(filename, index=False)
    print(f"\n✓ 已导出: {filename}")
except Exception as e:
    print(f"\n✗ 导出失败: {e}")

print("\n" + "="*80)
print("完成".center(80))
print("="*80)
